package cn.openea.perpartner.rule.util;

import cn.openea.perpartner.rule.compile.DynamicClassLoader;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @author Administrator
 */
@Component
public class SpringBeanUtil extends cn.hutool.extra.spring.SpringUtil {

    /**
     * 注册java源码代表的类到spring容器中
     *
     * @param javaCode Java源代码
     */
    public static void register(String javaCode) throws ClassNotFoundException {
        register(null, javaCode);
    }

    /**
     * 注册java源码代表的类到spring容器中
     *
     * @param beanName bean名称
     * @param javaCode Java源代码
     */
    public static void register(String beanName, String javaCode) throws ClassNotFoundException {
        //使用动态类加载器载入java源码得到Class对象
        Class<?> clazz = DynamicClassLoader.load(javaCode);
        register(beanName, clazz);
    }

    /**
     * 注册java源码代表的类到spring容器中
     *
     * @param beanName bean名称
     */
    public static void register(String beanName, Class<?> clazz) {
        //如果beanName传null，则赋值类的全限定名
        if (beanName == null) {
            beanName = clazz.getName();
        }
        //将applicationContext转换为ConfigurableApplicationContext
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) getApplicationContext();
        //获取bean工厂并转换为DefaultListableBeanFactory
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
        //若已经有了BeanDefinition了，先remove,否则容器启动没法多次调用
        //beanFactory.destroySingleton()了，BeanDefinition的注册只是放在了beanDefinitionMap中，还没
        //放入到singletonObjects这个map中，所以不能用destroySingleton()，这个是没效果的
        if (beanFactory.containsBeanDefinition(beanName)) {
            beanFactory.removeBeanDefinition(beanName);
        }
        //使用spring的BeanDefinitionBuilder将Class对象转成BeanDefinition
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        //以指定beanName注册生成的BeanDefinition
        beanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getRawBeanDefinition());
    }

    public static boolean beanIsExists(String ruleNum) {
        ApplicationContext context = getApplicationContext();
        String[] beanNames = context.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            if (beanName.trim().equals(ruleNum.trim())) {
                return true;
            }
        }
        return false;
    }
}
